﻿using UnityEngine;
using UnityEngine.UIElements;

namespace winS.UnityEditor.UIElement
{
    /// <summary>
    /// 开关
    /// </summary>
    public class Toggle : EditorField<bool>
    {
        public static readonly float size = 14f;
        public static readonly float maskSize = 10f;
        public static readonly float rightOffset = (size - maskSize) * 0.5f;
        public static readonly Color borderColor = new Color32(28, 28, 28, 255);

        private readonly Icon icon;
        private readonly EditorElement box;

        internal Toggle(ElementFactory elementFactory) : base(elementFactory)
        {
            style.alignItems = Align.Center;
            style.justifyContent = Justify.SpaceBetween;

            Add(box = EditorElementUtility.elementFactory.CreateEditorElementWithName("勾选框"));
            box.style.overflow = Overflow.Hidden;
            box.style.justifyContent = Justify.Center;
            box.style.SetBackgroundColor(ColorLevelUtility.GetColor(4));
            box.style.SetBorder(borderColor, 1f, 2f);
            box.style.SetSize(size);
            box.RegisterCallback<ClickEvent>(_ => value = !value);
            box.RegisterCallback<MouseDownEvent>(mouseDownEvent => mouseDownEvent.StopPropagation());
            EditorElementUtility.ApplyFocusElementStyle(box, elementFactory.borderColor);

            box.Add(icon = EditorElementUtility.elementFactory.CreateIcon(PackageAssets.Icons.tick, 12f));
            icon.style.display = DisplayStyle.None;
            icon.pickingMode = PickingMode.Ignore;
            icon.style.SetPadding(2f);
        }

        public override void SetValueWithoutNotify(bool value)
        {
            if (this.value == value) return;
            base.SetValueWithoutNotify(value);
            icon.style.display = value ? DisplayStyle.Flex : DisplayStyle.None;
        }

        protected override void SetValue(bool value)
        {
            base.SetValue(value);
            icon.style.display = value ? DisplayStyle.Flex : DisplayStyle.None;
        }
        protected override void OnRedo(bool newValue)
        {
            base.OnRedo(newValue);
            icon.style.display = value ? DisplayStyle.Flex : DisplayStyle.None;
        }
        protected override void OnUndo(bool oldValue)
        {
            base.OnUndo(oldValue);
            icon.style.display = value ? DisplayStyle.Flex : DisplayStyle.None;
        }
    }
}